﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.Appointment;
using BenCaoXuan.Infrastructure.Dto.Admin.Home;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Home_Service : Base_Service, I_Home_Service
    {
        private readonly Appointment_IOC _appointment_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Order_IOC _order_IOC;
        private readonly Product_IOC _product_IOC;

        public Home_Service(Appointment_IOC appointment_IOC,
            Customer_IOC customer_IOC,
            Product_IOC product_IOC,
            Order_IOC order_IOC
            )
        {
            _appointment_IOC = appointment_IOC;
            _customer_IOC = customer_IOC;
            _order_IOC=order_IOC;
            _product_IOC = product_IOC;
        }

        /// <summary>
        /// 获取近7日的收入趋势
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_IncomeTrend()
        {
            
                // 1. 计算近7日日期范围（包含今天，共7天）
                DateTime endDate = DateTime.Now.Date; // 今天（如：2025-10-13）
                DateTime startDate = endDate.AddDays(-6); // 7天前（如：2025-10-07）

                // 2. 获取近7日的订单数据
                var data = await _order_IOC._orders_EFCore
                    .GetAll(d => d.OCreateTime >= startDate && d.OCreateTime <= endDate.AddDays(1).AddTicks(-1) && d.OPayStatus==1) // 包含今天全天
                    .ToListAsync();

            // 3. 按星期几分组统计收入（1=周一，7=周日）
            var weeklyIncome = data
 .GroupBy(d =>
 {
     // 先判断可空的 DateTime 是否有值
     if (d.OCreateTime.HasValue)
     {
         int dayOfWeek = (int)d.OCreateTime.Value.DayOfWeek;
         return dayOfWeek == 0 ? 7 : dayOfWeek;
     }
     // 如果 OCreateTime 为 null，这里可以根据业务需求返回一个默认值，比如 0
     return 0;
 })
 .Select(g => new
 {
     WeekDay = g.Key,
     Income = g.Sum(d => d.OTotalAmount),
     DayName = g.Key switch
     {
         1 => "周一",
         2 => "周二",
         3 => "周三",
         4 => "周四",
         5 => "周五",
         6 => "周六",
         7 => "周日",
         _ => ""
     }
 })
 .OrderBy(g => g.WeekDay)
 .ToList();

            // 4. 确保周一到周日都有数据（无数据的日期收入为0）
            var resultData = new List<object>();
                for (int i = 1; i <= 7; i++)
                {
                    var item = weeklyIncome.FirstOrDefault(w => w.WeekDay == i);
                    resultData.Add(new
                    {
                        WeekDay = i,
                        DayName = i switch
                        {
                            1 => "周一",
                            2 => "周二",
                            3 => "周三",
                            4 => "周四",
                            5 => "周五",
                            6 => "周六",
                            7 => "周日",
                            _ => ""
                        },
                        Income = item?.Income ?? 0 // 无数据则收入为0
                    });
                }

                // 5. 提取纯收入数组（与前端模拟格式匹配）
                var revenueData = resultData.Select(r => ((dynamic)r).Income).ToList();

            return Get_Result(0, "ok", revenueData);
            
          
        }

        /// <summary>
        /// 获取订单统计数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_OrderData()
        {
           OrderData_Dto data=new OrderData_Dto();

            //总订单数
            data.totalOrders =await _order_IOC._orders_EFCore.GetAll().CountAsync();
            //已完成订单数
            data.completedOrders = await _order_IOC._orders_EFCore.GetAll(d => d.OOrderStatus == 1).CountAsync();
            //待处理订单数
            data.pendingOrders = await _order_IOC._orders_EFCore.GetAll(d => d.OOrderStatus == 0).CountAsync();
            //总收益
            data.totalRevenue =(double) await _order_IOC._orders_EFCore.GetAll(d => d.OPayStatus == 1).SumAsync(d => d.OTotalAmount);

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取今日的预约订单
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_TodayAppointment(Fenye_Dto dto)
        {
            // 获取今天的起始和结束时间（UTC+8时区处理，避免时区问题）
            var todayStart = DateTime.Now.Date; // 今天00:00:00
            var todayEnd = todayStart.AddDays(1).AddTicks(-1); // 今天23:59:59.999

            // 获取预约主数据（修正查询条件）
            var mainData = await _appointment_IOC._appointment_EFCore
                .GetAll(out int total, dto.page, dto.limit, false,
                        order => order.APeriod,
                        d =>(d.APeriod>=todayStart && d.APeriod<=todayEnd) 
                        )
                .Select(d => new Appointment_Dto
                {
                    id = d.AId,
                    date = d.APeriod.Value.ToString("yyyy-MM-dd"),
                    time = d.ATime,
                    price = d.AMoney,
                    status = d.AStatus,
                    name = d.ACustomerName,
                    phone = d.APhone,
                    allSpecsID = d.AProductId, // 规格ID，逗号分隔
                    packagesId = d.APackageId, // 套餐ID，逗号分隔
                    services = new List<Appointment_Services_Dto>()
                })
                .ToListAsync();

            // 预加载关联数据（不变）
            var allProductPackages = _product_IOC._productPackage_EFCore.GetAll().ToList();
            var allProductSpecs = _product_IOC._productSpecs_EFCore.GetAll().ToList();
            var allProducts = _product_IOC._product_EFCore.GetAll().ToList();

            // 处理服务项（不变）
            foreach (var item in mainData)
            {
                // 1. 处理多套餐
                if (!string.IsNullOrEmpty(item.packagesId))
                {
                    var packageIds = item.packagesId.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (packageIds.Length > 0)
                    {
                        var packages = allProductPackages.Where(p => packageIds.Contains(p.PpId)).ToList();
                        foreach (var package in packages)
                        {
                            item.services.Add(new Appointment_Services_Dto
                            {
                                name = package.PpName,
                                price = Convert.ToInt32(package.PpPrice)
                            });
                        }
                    }
                }

                // 2. 处理多产品规格
                if (!string.IsNullOrEmpty(item.allSpecsID))
                {
                    var specIds = item.allSpecsID.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (specIds.Length > 0)
                    {
                        var specs = allProductSpecs.Where(s => specIds.Contains(s.PsId)).ToList();
                        foreach (var spec in specs)
                        {
                            var product = allProducts.FirstOrDefault(p => p.PId == spec.PsProductId);
                            if (product != null)
                            {
                                item.services.Add(new Appointment_Services_Dto
                                {
                                    name = product.PName,
                                    price = Convert.ToInt32(spec.PsPrice)
                                });
                            }
                        }
                    }
                }
            }

            return Get_Result(0, "ok", new { data = mainData, total = total });
        }

        /// <summary>
        /// 获取今日数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Today_Data()
        {
           TodayData_Dto data=new TodayData_Dto();
            // 获取今天的起始和结束时间（UTC+8时区处理，避免时区问题）
            var todayStart = DateTime.Now.Date; // 今天00:00:00
            var todayEnd = todayStart.AddDays(1).AddTicks(-1); // 今天23:59:59.999

            //今日预约数
            data.appointmentToday =await _appointment_IOC._appointment_EFCore
                .GetAll(d => d.APeriod >= todayStart && d.APeriod <= todayEnd).CountAsync();

            //今日订单数
            var order = await _order_IOC._orders_EFCore
                 .GetAll(d => d.OCreateTime >= todayStart && d.OCreateTime <= todayEnd).ToListAsync() ;

            data.orderToday = order.Count();
            //今日收入
            data.moneyToday =(double?)order.Where(d => d.OPayStatus==1).Sum(d => d.OTotalAmount);
            //今日新客户
            data.customerToday =await _customer_IOC._customer_EFCore
                .GetAll(d => d.CCreateTime >= todayStart && d.CCreateTime <= todayEnd)
                .CountAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取消费top5的客户信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_TopCustomer()
        {
            // 1. 从订单表按客户分组，统计订单数、总消费金额
            var topCustomers = await _order_IOC._orders_EFCore
                .GetAll(d=>d.OPayStatus==1) // 获取所有订单
                .GroupBy(o => new
                {
                    CustomerPhone = o.OCustomerPhone,
                    CustomerName = o.OCustomerName 
                })
                .Select(g => new
                {
                    CustomerPhone = g.Key.CustomerPhone,
                    CustomerName = g.Key.CustomerName ?? "未知客户", // 处理客户名称为空的情况
                    OrderCount = g.Count(), // 订单总数
                    TotalSpent = g.Sum(o => o.OTotalAmount), // 总消费金额（假设订单总金额字段为O_TotalAmount）
                    AvgOrderAmount = g.Count() > 0 ? g.Sum(o => o.OTotalAmount) / g.Count() : 0 // 平均订单金额
                })
                .OrderByDescending(c => c.OrderCount)
    .ThenByDescending(c => c.TotalSpent)
                .Take(5) // 取前五名
                .ToListAsync();

            // 2. 补充排名信息
            var data = topCustomers.Select((customer) => new TopCustomer_Dto
            {

                customerPhone = customer.CustomerPhone,
                customerName = customer.CustomerName,
                orderCount = customer.OrderCount,
                totalSpent =(double) customer.TotalSpent!,
                avgOrderAmount = Math.Round((double)customer.AvgOrderAmount!, 2) // 保留两位小数
            }).ToList();

            return Get_Result(0, "ok", data);
            
        }
    }
}
